<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <!-- 使用el-row和el-col实现一行两列布局 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数据类型" prop="dataType">
              <el-select v-model="formData.dataType" placeholder="请选择数据类型" style="width: 100%;">
                <el-option v-for="item in dataTypeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="formData.deviceType" placeholder="请选择设备类型" style="width: 100%;">
                <el-option v-for="item in deviceTypeList" :key="item.value" :label="item.label" :value="Number(item.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备" prop="deviceCode">
              <el-select
                v-model="formData.deviceCode"
                placeholder="请选择设备"
                filterable
                remote
                :remote-method="remoteDeviceSearch"
                :loading="deviceLoading"
                @change="handleDeviceChange"
                style="width: 100%"
              >
                <el-option v-for="item in deviceList" :key="item.id" :label="item.deviceName" :value="item.deviceCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产线" prop="deptId">
              <treeselect v-model="formData.deptId" :options="deptOptions" :flat="true" :normalizer="normalizer"
                          placeholder="选择产线" style="width: 100%" :default-expand-all="true" @select="handleDeptSelect"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工位" prop="postId">
              <el-select v-model="formData.postId" placeholder="请选择工位" filterable style="width: 100%"
                         @change="handlePostChange" :disabled="!formData.deptId">
                <el-option v-for="item in postList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作员" prop="operatorId">
              <el-select v-model="formData.operatorId" placeholder="请选择操作员" filterable style="width: 100%"
                         @change="changeUser">
                <el-option v-for="item in userList" :key="item.id" :label="item.username" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作员工号" prop="operatorIdCard">
              <el-input v-model="formData.operatorIdCard" readonly placeholder="请输入操作员工号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事件类型" prop="eventType">
              <el-select v-model="formData.eventType" placeholder="请选择事件类型" @change="handleEventTypeChange"  style="width: 100%;">
                <el-option v-for="item in eventTypeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作时间" prop="operationTime">
              <el-date-picker clearable v-model="formData.operationTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择操作时间" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="记录状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="item in statusList" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as EventRecordApi from '@/api/lamp/eventrecord';
import { getDictDatas, DICT_TYPE } from '@/utils/dict';
import { listDept } from '@/api/system/dept';
import { listUser } from '@/api/system/user';
import { listPost } from '@/api/system/post';
import * as DeviceApi from '@/api/lamp/device/index.js';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "EventRecordForm",
  components: {
    Treeselect
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 设备列表加载状态
      deviceLoading: false,
      // 设备类型字典
      deviceTypeList: getDictDatas(DICT_TYPE.DEVICE_TYPE),
      // 数据类型数组
      dataTypeList: [
        { label: '正常生产', value: 1 },
        { label: '返工', value: 2 },
        { label: '试产', value: 3 }
      ],
      // 事件类型数组
      eventTypeList: [
        { label: '下线', value: 0 },
        { label: '上线', value: 1 },
        { label: '复位', value: 2 },
        { label: '缺人', value: 3 },
        { label: '缺料', value: 4 },
        { label: '其他', value: 5 },
        { label: '换线', value: 6 },
        { label: '品质异常', value: 7 },
        { label: '设备&测试异常', value: 8 },
        { label: '取消', value: 9 }
      ],
      // 记录状态数组
      statusList: [
        { label: '有效', value: 1 },
        { label: '无效', value: 0 }
      ],
      // 产线树选项
      deptOptions: [],
      // 用户列表
      userList: [],
      // 工位列表
      postList: [],
      // 设备列表
      deviceList: [],
      // 表单参数
      formData: {
        id: undefined,
        dataType: undefined,
        deviceType: undefined,
        deviceCode: undefined,
        deviceName: undefined,
        deptId: undefined,
        deptName: undefined,
        postId: undefined,
        postName: undefined,
        eventType: undefined,
        eventName: undefined,
        operatorId: undefined,
        operatorName: undefined,
        operatorIdCard: undefined,
        operationTime: undefined,
        status: '1',
      },
      // 表单校验
      formRules: {
        dataType: [{ required: true, message: '数据类型不能为空', trigger: 'change' }],
        deviceType: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
        deviceCode: [{ required: true, message: '设备不能为空', trigger: 'change' }],
        deptId: [{ required: true, message: '产线不能为空', trigger: 'change' }],
        eventType: [{ required: true, message: '事件类型不能为空', trigger: 'change' }],
        eventName: [{ required: true, message: '事件名称不能为空', trigger: 'blur' }],
        operatorIdCard: [{ required: true, message: '操作员工号不能为空', trigger: 'blur' }],
        operationTime: [{ required: true, message: '操作时间不能为空', trigger: 'blur' }],
      },
    };
  },
  created() {
    this.getOptions();
  },
  watch: {
    'formData.deptId'(newVal) {
      // 当产线改变时，清空工位选择
      if (newVal !== undefined) {
        this.formData.postId = undefined;
        this.formData.postName = undefined;
      }
    }
  },
  methods: {
    /** 获取下拉框选项 */
    async getOptions() {
      try {
        // 获取所有产线列表（包括所有层级）
        const deptRes = await listDept({ pageNo: 1, pageSize: 100 });
        // 处理产线树数据
        this.deptOptions = this.addLevelToNodes(this.handleTree(deptRes.data, "id"), 1);

        // 获取用户列表
        const userRes = await listUser({ pageSize: 100, pageNo: 1 });
        this.userList = userRes.data.list;

        // 初始化工位列表为空，不预先加载所有工位
        this.postList = [];
      } catch (error) {
        this.$modal.msgError('获取数据失败');
      }
    },

    // 递归函数为节点添加层级标记
    addLevelToNodes(nodes, currentLevel = 1) {
      if (!nodes || !Array.isArray(nodes)) {
        return [];
      }
      return nodes.map(node => {
        const newNode = {
          ...node,
          level: currentLevel
        };
        if (node.children && node.children.length > 0) {
          newNode.children = this.addLevelToNodes(node.children, currentLevel + 1);
        }
        return newNode;
      });
    },

    // 产线树数据格式化
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children
      };

      // 如果不是type==3的产线，则禁用
      if (node.deptType !== 3) {
        normalizedNode.isDisabled = true;
      }
      return normalizedNode;
    },
    handleEventTypeChange(eventType) {
      const eventTypeItem = this.eventTypeList.find(item => item.value === eventType);
      if (eventTypeItem) {
        this.formData.eventName = eventTypeItem.label;
      }
    },
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await EventRecordApi.getEventRecord(id);
          this.formData = res.data;
          this.dialogTitle = "修改上报事件";
          // 如果有产线ID，加载对应的工位列表
          if (this.formData.deptId) {
            await this.getPostsByDeptId(this.formData.deptId);
          }
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增上报事件";
      }
    },

    /** 处理产线选择 */
    async handleDeptSelect(deptId) {
      if (deptId) {
        this.formData.deptName = deptId.name;
        // 清空工位选择
        this.formData.postId = undefined;
        this.formData.postName = undefined;
        // 根据产线ID查询工位
        await this.getPostsByDeptId(deptId.id);
      }
    },

    /** 根据产线ID查询工位 */
    async getPostsByDeptId(deptId) {
      try {
        const res = await listPost({ pageSize: 100, pageNo: 1, deptId: deptId });
        this.postList = res.data.list;
      } catch (error) {
        this.$modal.msgError('获取工位列表失败');
        this.postList = [];
      }
    },

    /** 处理工位选择 */
    handlePostChange(postId) {
      const post = this.postList.find(item => item.id === postId);
      if (post) {
        this.formData.postName = post.postName;
      }
    },

    /** 处理用户选择 */
    changeUser(userId) {
      const user = this.userList.find(item => item.id === userId);
      if (user) {
        this.formData.operatorName = user.username;
        this.formData.operatorIdCard = user.idCard;
      }
    },

    /** 设备远端搜索 */
    async remoteDeviceSearch(query) {
      if (query) {
        this.deviceLoading = true;
        try {
          const res = await DeviceApi.getDevicePage({
            pageNo: 1,
            pageSize: 20,
            deviceName: query,
          });
          this.deviceList = res.data.list;
        } finally {
          this.deviceLoading = false;
        }
      } else {
        this.deviceList = [];
      }
    },

    /** 处理设备选择 */
    handleDeviceChange(deviceCode) {
      const device = this.deviceList.find(item => item.deviceCode === deviceCode);
      if (device) {
        this.formData.deviceName = device.deviceName;
        this.formData.deviceType = device.deviceType;
      }
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await EventRecordApi.updateEventRecord(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await EventRecordApi.createEventRecord(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },

    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        dataType: undefined,
        deviceType: undefined,
        deviceCode: undefined,
        deviceName: undefined,
        deptId: undefined,
        deptName: undefined,
        postId: undefined,
        postName: undefined,
        eventType: undefined,
        eventName: undefined,
        operatorId: undefined,
        operatorName: undefined,
        operatorIdCard: undefined,
        operationTime: undefined,
        status: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>
